package com.atguigu.gmall.realtime.app.dwm;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.gmall.realtime.utils.MyKafkaUtil;
import org.apache.flink.api.common.eventtime.SerializableTimestampAssigner;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.cep.CEP;
import org.apache.flink.cep.PatternFlatSelectFunction;
import org.apache.flink.cep.PatternFlatTimeoutFunction;
import org.apache.flink.cep.PatternStream;
import org.apache.flink.cep.pattern.Pattern;
import org.apache.flink.cep.pattern.conditions.SimpleCondition;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.connectors.kafka.FlinkKafkaConsumer;
import org.apache.flink.util.Collector;
import org.apache.flink.util.OutputTag;

import java.time.Duration;
import java.util.List;
import java.util.Map;

/**
 * Author: Felix
 * Date: 2021/11/29
 * Desc: 用户跳出明细计算
 *需要启动的进程
 *      zk、kafka、logger.sh、BaseLogApp、UserJumpDetailApp
 *执行流程
 *      -运行模拟生成日志的jar包(前端埋点产生日志)
 *      -发送给nginx进行负载均衡
 *      -nginx将请求转发给日志采集服务
 *      -日志采集服务主要完成的功能
 *          打印输出到控制台
 *          落盘
 *          发送到kafka的主题ods_base_log
 *      -BaseLogApp从ods_base_log中读取数据，进行分流
 *          启动日志    dwd_start_log
 *          页面日志    dwd_page_log
 *          曝光日志    dwd_display_log
 *      -UserJumpDetailApp从dwd_page_log中读取页面访问情况，判断是否为跳出行为
 *          定义pattern
 *          将pattern应用到流上
 *          从流中提取数据
 *              >超时数据
 *              >完全匹配的数据
 *      -将超时数据提取出来，就是我们要得到跳出明细，将跳出明细写到kafka的dwm_user_jump_detail
 *
 *
 */
public class UserJumpDetailApp {
    public static void main(String[] args) throws Exception {
        //TODO 1.基本环境准备
        //1.1 设置流处理环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        //1.2 设置并行度
        env.setParallelism(4);

        //TODO 2.设置检查点(略)

        //TODO 3.从Kafka中读取数据
        //3.1 声明消费主题以及消费者组
        String topic = "dwd_page_log";
        String groupId = "user_jump_detail_app_group";

        //3.2 创建消费者对象
        FlinkKafkaConsumer<String> kafkaSource = MyKafkaUtil.getKafkaSource(topic, groupId);

        //3.3 消费数据封装流
        DataStreamSource<String> kafkaDS = env.addSource(kafkaSource);
        /*DataStream<String> kafkaDS = env
            .fromElements(
                "{\"common\":{\"mid\":\"101\"},\"page\":{\"page_id\":\"home\"},\"ts\":10000} ",
                "{\"common\":{\"mid\":\"102\"},\"page\":{\"page_id\":\"home\"},\"ts\":12000}",
                "{\"common\":{\"mid\":\"102\"},\"page\":{\"page_id\":\"good_list\",\"last_page_id\":" +
                    "\"home\"},\"ts\":15000} ",
                "{\"common\":{\"mid\":\"102\"},\"page\":{\"page_id\":\"good_list\",\"last_page_id\":" +
                    "\"detail\"},\"ts\":30000} "
            );
*/

        //TODO 4.对流中的数据进行类型转换   jsonStr->jsonObj
        SingleOutputStreamOperator<JSONObject> jsonObjDS = kafkaDS.map(JSON::parseObject);

        //TODO 5.指定watermark以及提取事件时间字段
        SingleOutputStreamOperator<JSONObject> jsonObjWithWatermarkDS = jsonObjDS.assignTimestampsAndWatermarks(
            //WatermarkStrategy.<JSONObject>forMonotonousTimestamps()
            WatermarkStrategy.<JSONObject>forBoundedOutOfOrderness(Duration.ofSeconds(3))
                .withTimestampAssigner(
                    new SerializableTimestampAssigner<JSONObject>() {
                        @Override
                        public long extractTimestamp(JSONObject jsonObj, long recordTimestamp) {
                            return jsonObj.getLong("ts");
                        }
                    }
                )
        );

        //jsonObjWithWatermarkDS.print(">>>>>>");

        //TODO 6. 按照mid进行分组
        KeyedStream<JSONObject, String> keyedDS = jsonObjWithWatermarkDS.keyBy(jsonObj -> jsonObj.getJSONObject("common").getString("mid"));

        //TODO 7. 使用FlinkCEP 按照指定的pattern，从流中将匹配的数据过滤处理
        //7.1 定义pattern
        Pattern<JSONObject, JSONObject> pattern = Pattern.<JSONObject>begin("first").where(
            new SimpleCondition<JSONObject>() {
                @Override
                public boolean filter(JSONObject jsonObj) {
                    //获取lastpageId
                    String lastPageId = jsonObj.getJSONObject("page").getString("last_page_id");
                    if (lastPageId == null || lastPageId.length() == 0) {
                        return true;
                    }
                    return false;
                }
            }
        ).next("second").where(
            new SimpleCondition<JSONObject>() {
                @Override
                public boolean filter(JSONObject jsonObj) {
                    String pageId = jsonObj.getJSONObject("page").getString("page_id");
                    if (pageId != null && pageId.length() > 0) {
                        return true;
                    }
                    return false;
                }
            }
        ).within(Time.seconds(10));

        //7.2 将pattern应用到流上
        PatternStream<JSONObject> patternDS = CEP.pattern(keyedDS, pattern);

        //7.3 从流中提取数据
        //注意：超时数据会放到侧输出流中，所有我们需要定义侧输出流标签
        OutputTag<String> timeoutTag = new OutputTag<String>("timeoutTag"){};
        SingleOutputStreamOperator<String> resDS = patternDS.flatSelect(
            timeoutTag,
            new PatternFlatTimeoutFunction<JSONObject, String>() {
                @Override
                public void timeout(Map<String, List<JSONObject>> pattern, long timeoutTimestamp, Collector<String> out) throws Exception {
                    //处理超时数据
                    List<JSONObject> jsonObjList = pattern.get("first");
                    for (JSONObject jsonObj : jsonObjList) {
                        //注意：将和first匹配的元素(跳出行为) 向下游传递   out.collect将超时元素放到侧输出流中
                        out.collect(jsonObj.toJSONString());
                    }
                }
            },
            new PatternFlatSelectFunction<JSONObject, String>() {
                @Override
                public void flatSelect(Map<String, List<JSONObject>> pattern, Collector<String> out) throws Exception {
                    //处理完全匹配的数据   如果完全匹配的数据，属于跳转 不在我们的需求范围内，所以这个方法中不需要有什么实现
                }
            }
        );

        //7.4 从侧输出流中获取跳出明细
        DataStream<String> timeoutDS = resDS.getSideOutput(timeoutTag);

        timeoutDS.print(">>>>>>");

        //TODO 8.将跳出明细数据写到kafka主题中
        timeoutDS.addSink(MyKafkaUtil.getKafkaSink("dwm_user_jump_detail"));

        env.execute();
    }

}
